package models

import (
	"database/sql"
	"easy-gin/drivers"
	"log"
)

var FILE_TYPE_IMAGE = 0
var FILE_TYPE_MUSIC = 1
var FILE_TYPE_VIDEO = 2
var FILE_TYPE_DOC = 3
var FILE_TYPE_OTHER = 4

var FILE_IMAGE_TABLE = "images"
var FILE_MUSIC_TABLE = "musics"
var FILE_VIDEO_TABLE = "videos"
var FILE_DOC_TABLE = "docs"
var FILE_OTHER_TABLE = "others"

type FileDao struct {
	Id   int    `json:"id" form:"id" primaryKey:"true"`
	Name string `json:"name" form:"name"`
	Size int    `json:"size" form:"size"`
}

func AddSqlFileInfo(fileType int, name string, size int64) (result sql.Result, err error) {
	if drivers.MysqlConnect != true {
		return
	}

	result, err = db.Exec("INSERT INTO `"+GetTable(fileType)+"`(`name`, `size`) values(?, ?)", name, size)
	return
}

func (model *FileDao) GetSqlFileInfoFromId(id string, fileType int, page int, pageSize int) (fileDaoInfo FileDao, err error) {
	if drivers.MysqlConnect != true {
		return
	}

	err = db.QueryRow("SELECT `id`, `name`, `size` FROM `"+GetTable(fileType)+"` WHERE `id` = ?", id).Scan(&fileDaoInfo.Id, &fileDaoInfo.Name, &fileDaoInfo.Size)
	if err != nil {
		log.Println(err.Error())
		return
	}

	return
}

// get list
func GetSqlFilesInfo(fileType int, page int, pageSize int) (fileDaos []FileDao, err error) {
	if drivers.MysqlConnect != true {
		return
	}

	fileDaos = make([]FileDao, 0)

	offset := pageSize * (page - 1)
	limit := pageSize

	var sqlStr = "SELECT `id`, `name`, `size` FROM `" + GetTable(fileType) + "` LIMIT ?, ?"

	rows, err := db.Query(sqlStr, offset, limit)
	defer rows.Close()

	if err != nil {
		log.Println(err.Error())
		return
	}

	var fileDao FileDao
	for rows.Next() {
		rows.Scan(&fileDao.Id, &fileDao.Name, &fileDao.Size)
		fileDaos = append(fileDaos, fileDao)
	}

	if err = rows.Err(); err != nil {
		log.Println(err.Error())
	}

	return
}

func (model *FileDao) DeleteSqlFileInfo(fileType int, id string) (result sql.Result, err error) {
	if drivers.MysqlConnect != true {
		return
	}

	result, err = db.Exec("DELETE from `"+GetTable(fileType)+"` where id=?", id)
	return
}

func GetTable(fileType int) string {
	switch fileType {
	case FILE_TYPE_IMAGE: //图片
		return FILE_IMAGE_TABLE
	case FILE_TYPE_MUSIC: //音乐
		return FILE_MUSIC_TABLE
	case FILE_TYPE_VIDEO: //视频
		return FILE_VIDEO_TABLE
	case FILE_TYPE_DOC: //文档
		return FILE_DOC_TABLE
	}
	return FILE_OTHER_TABLE
}
